package name.fowler.refactoring.simplestore.reporter.impl;

import java.util.List;

import name.fowler.refactoring.simplestore.reporter.IFormatter;
import name.fowler.refactoring.simplestore.reporter.report.Cell;
import name.fowler.refactoring.simplestore.reporter.report.Report;
import name.fowler.refactoring.simplestore.reporter.report.Row;
import name.fowler.refactoring.simplestore.reporter.report.Table;

public class PlainTextFormatter implements IFormatter {

	private StringBuilder formatCell(Cell cell) {
		return new StringBuilder(cell.getValue());
	}
	
	private StringBuilder formatRow(Row row) {
		StringBuilder rowStr = new StringBuilder();
		List <Cell> cells = row.getCells();
		int i = 0;
		for (Cell cell : cells) {
			rowStr.append(formatCell(cell));
			if (i < cells.size() - 1) {
				rowStr.append("\t");
			}
			i++;
		}
		return rowStr;
	}
	
	private StringBuilder formatTable(Table table) {
		StringBuilder tableStr = new StringBuilder();
		if (table != null) {
			List<Row> rows = table.getRows();
			int i = 0;
			for (Row row : rows) {
				tableStr.append(formatRow(row));
				if (i < rows.size() - 1) {
					tableStr.append("\n");
				}
				i++;
			}
		}
		return tableStr;
	}
	
	
	@Override
	public String formatReport(Report report) {
		// TODO Auto-generated method stub
		StringBuilder result = new StringBuilder();
		result.append(formatTable(report.getHeader()));
		result.append('\n');
		result.append(formatTable(report.getTitle()));
		result.append('\n');
		result.append(formatTable(report.getBody()));
		result.append('\n');
		result.append(formatTable(report.getFooter()));
		return result.toString();
	}

}
